<template>
  <div class="login">
    <div class="container-fluid p-0">
      <div class="row g-0">
        <!-- Left Banner Section -->
        <div class="col-md-6 banner-section">
          <div class="banner-content">
            <h1 class="display-4">命理定义</h1>
            <p class="lead">探索命理的奥秘，了解人生的真谛</p>
            <img src="/images/login-banner.jpg" alt="Login Banner" class="banner-image">
          </div>
        </div>

        <!-- Right Login Form Section -->
        <div class="col-md-6 login-form-section">
          <div class="login-form-container">
            <div class="card">
              <div class="card-header">
                <h3 class="text-center">登录</h3>
              </div>
              <div class="card-body">
                <!-- 成功提示 -->
                <div v-if="alertMessage.show && alertMessage.type === 'success'" 
                     class="alert alert-success alert-dismissible fade show" 
                     role="alert">
                  {{ alertMessage.text }}
                  <button type="button" class="btn-close" @click="closeAlert"></button>
                </div>
                
                <!-- 错误提示 -->
                <div v-if="alertMessage.show && alertMessage.type === 'danger'" 
                     class="alert alert-danger alert-dismissible fade show" 
                     role="alert">
                  {{ alertMessage.text }}
                  <button type="button" class="btn-close" @click="closeAlert"></button>
                </div>
                
                <form @submit.prevent="handleLogin">
                  <div class="mb-3">
                    <label for="username" class="form-label">用户名</label>
                    <input 
                      type="text" 
                      class="form-control" 
                      :class="{ 'is-invalid': errors.username }"
                      id="username" 
                      v-model="username" 
                      @input="validateUsername"
                      required
                    >
                    <div class="invalid-feedback" v-if="errors.username">
                      {{ errors.username }}
                    </div>
                  </div>
                  <div class="mb-3">
                    <label for="password" class="form-label">密码</label>
                    <input 
                      type="password" 
                      class="form-control" 
                      :class="{ 'is-invalid': errors.password }"
                      id="password" 
                      v-model="password" 
                      @input="validatePassword"
                      required
                    >
                    <div class="invalid-feedback" v-if="errors.password">
                      {{ errors.password }}
                    </div>
                  </div>
                  <div class="mb-3 form-check">
                    <input type="checkbox" class="form-check-input" id="rememberMe" v-model="rememberMe">
                    <label class="form-check-label" for="rememberMe">记住我</label>
                  </div>
                  <div class="d-grid gap-2">
                    <button 
                      type="submit" 
                      class="btn btn-primary" 
                      :disabled="isLoading || !isFormValid"
                    >
                      <span v-if="isLoading" class="spinner-border spinner-border-sm me-2"></span>
                      {{ isLoading ? '登录中...' : '登录' }}
                    </button>
                    <router-link to="/register" class="btn btn-outline-secondary">
                      没有账号？立即注册
                    </router-link>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { useUserStore } from '../store/userStore'
import authService from '../api'

export default {
  name: 'Login',
  data() {
    return {
      username: '',
      password: '',
      rememberMe: false,
      isLoading: false,
      alertMessage: {
        show: false,
        type: '',
        text: ''
      },
      errors: {
        username: '',
        password: ''
      }
    }
  },
  computed: {
    isFormValid() {
      return !Object.values(this.errors).some(error => error) &&
             this.username && this.password
    }
  },
  methods: {
    closeAlert() {
      this.alertMessage.show = false;
    },
    showAlert(type, text) {
      this.alertMessage = {
        show: true,
        type,
        text
      };
      
      // 5秒后自动关闭提示
      setTimeout(() => {
        this.alertMessage.show = false;
      }, 5000);
    },
    validateUsername() {
      if (!this.username) {
        this.errors.username = '请输入用户名'
      } else {
        this.errors.username = ''
      }
    },
    validatePassword() {
      if (!this.password) {
        this.errors.password = '请输入密码'
      } else {
        this.errors.password = ''
      }
    },
    async handleLogin() {
      if (!this.isFormValid) return

      this.isLoading = true
      try {
        // 使用Pinia存储中的登录方法
        const userStore = useUserStore();
        const result = await userStore.login(this.username, this.password);
        
        if (!result.success) {
          if (result.isNetworkError) {
            console.error('网络错误:', result.error);
            this.showAlert('danger', '网络请求失败，可能是跨域(CORS)问题。请联系管理员。');
            return;
          }
          throw new Error(result.error);
        }
        
        // 用户数据已在login方法中处理，这里不需要再调用fetchUserInfo
        // 只更新积分信息即可
        try {
          await userStore.getUserScore();
        } catch (error) {
          console.error('获取积分失败:', error);
          // 获取积分失败不影响登录流程
        }
        
        // 如果选择了"记住我"，可以设置更长的过期时间
        if (this.rememberMe) {
          localStorage.setItem('rememberMe', 'true');
          // 设置一个30天后的过期时间戳
          const expiryDate = new Date();
          expiryDate.setDate(expiryDate.getDate() + 30);
          localStorage.setItem('tokenExpiry', expiryDate.getTime().toString());
        } else {
          // 默认会话结束后过期
          localStorage.removeItem('rememberMe');
          localStorage.removeItem('tokenExpiry');
        }
        
        // 显示成功提示
        this.showAlert('success', '登录成功！正在跳转...');
        
        // 2秒后跳转到首页
        setTimeout(() => {
          this.$router.push('/');
        }, 2000);
      } catch (error) {
        console.error('登录失败:', error);
        this.showAlert('danger', error.message || '用户名或密码错误，请重试');
        this.errors.username = '用户名或密码错误';
        this.errors.password = '用户名或密码错误';
      } finally {
        this.isLoading = false;
      }
    }
  }
}
</script>

<style scoped>
.login {
  min-height: 100vh;
}

.banner-section {
  background: linear-gradient(135deg, #42b983 0%, #2c3e50 100%);
  min-height: 100vh;
  color: white;
  display: flex;
  align-items: center;
  position: relative;
  overflow: hidden;
  padding: 0;
}

.banner-content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 2;
  padding: 2rem;
  background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.4));
}

.banner-content h1 {
  font-size: 3.5rem;
  font-weight: 700;
  margin-bottom: 1.5rem;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
  background: linear-gradient(45deg, #fff, #f0f0f0);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  padding: 0.5rem 1rem;
  border-radius: 8px;
  position: relative;
}

.banner-content h1::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 80%;
  height: 4px;
  background: linear-gradient(90deg, transparent, #fff, transparent);
}

.banner-content p {
  font-size: 1.25rem;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
  max-width: 80%;
  text-align: center;
  line-height: 1.6;
  background: rgba(0, 0, 0, 0.3);
  padding: 1rem 2rem;
  border-radius: 4px;
}

.banner-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  opacity: 0.7;
  filter: blur(1px);
}

.login-form-section {
  min-height: 100vh;
  background-color: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-form-container {
  width: 100%;
  max-width: 400px;
  padding: 2rem;
}

.login .card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .banner-section {
    min-height: 40vh;
  }
  
  .login-form-section {
    min-height: 60vh;
  }
}
</style> 